/*
 * $Id$
 */
package py.windmill.action;

/**
 *
 * @author myang
 */
public class Execution {

    /**
     *
     * @param rt
     * @param req
     * @return
     */
    public void execute(final Route rt, final Request req) {

        req.params(rt.parse(req.requestUri()));

        final Resolution resolution = rt.resolution(req);
        req.response().contentType(resolution.produce());

        final Action action = rt.action();
        try {
            final ValidationErrors errors = action.validate(req);
            if (null == errors || errors.isEmpty()) {
                final Object obj = execute(action, req);
                if (obj instanceof Resolution) {
                    final Resolution res = (Resolution)obj;
                    res.execute(req, req.response());
                }
                else {
                    resolution.execute(req, obj);
                }
            } else {
                resolution.onErrors(req, errors);
            }
        }
        catch (Exception ex) {
            resolution.onException(req, ex);
        }
    }

    /**
     *
     * @param action
     * @param req
     * @return
     */
    private Object execute(final Action action, final Request req) throws Exception {
        if (req.is(HttpMethod.GET)) {
            return action.onGet(req);
        } else if (req.is(HttpMethod.POST)) {
            return action.onPost(req);
        }
        throw new RuntimeException("unsupported method: " + req.method());
    }
}
